package br.com.nautical.email.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

/*
 * Open Session
 */

public class ConexaoHibernateUtil implements Filter{

	private SessionFactory sf;
	
	@Override
	public void destroy() {
		
		
	}

	@Override
	public void doFilter(ServletRequest servletReqFilter, ServletResponse servletRespFilter,
			FilterChain chain) throws IOException, ServletException {
		
		try{
			//Abre uma conexão
			this.sf.getCurrentSession().beginTransaction();
			//Passa request e response para 'chain'
			chain.doFilter(servletReqFilter, servletRespFilter);
			//Commita
			this.sf.getCurrentSession().getTransaction().commit();
			//Fecha conexão
			this.sf.getCurrentSession().close();
			
		} catch (Throwable ex) {
			
			/*
			 * Caso ocorra exception durante conexão ativa
			 * existe necessidade de da um rollback 
			 */
			try {
				//Verif. se conexao esta ativa
				if(this.sf.getCurrentSession().getTransaction().isActive()){
					this.sf.getCurrentSession().getTransaction().rollback();
				}	
			} catch (Throwable e) {
				e.printStackTrace();
			}
			
			throw new ServletException();
		}
		
	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
		this.sf = HibernateUtil.getSession();
		
	}

	
}
